<?php

namespace aliyun;

class oss {
	protected $id= '';
	protected $key= '';
	protected $host = '';
	public function __construct($config){
		$this->id= $config['id'];
		$this->key= $config['key'];
		$this->host = $config['host'];
	}
	public function getPolicy($path,$maxSize=5000000){
		$now = time();
	    $expire = 600; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
	    $end = $now + $expire;
	    $expiration = $this->_gmt_iso8601($end);
	    $policy = [
	        'expiration'=>$expiration,
	        'conditions'=>[
	            ['content-length-range', 1, $maxSize],
	            ['starts-with', '$key', $path],
	        ]
	    ];
	    $policy = json_encode($policy);
	    $policy = base64_encode($policy);
	    $signature = base64_encode(hash_hmac('sha1', $policy, $this->key, true));

	    $response = array();
	    $response['OSSAccessKeyId'] = $this->id;
	    $response['AccessKeySecret'] = $this->key;
	    $response['policy'] = $policy;
	    $response['Signature'] = $signature;
	    $response['host'] = $this->host;
	    $response['expire'] = $end;
	    // $response['success_action_redirect'] = '';
	    $response['success_action_status'] = 200;
	    //这个参数是设置用户上传指定的前缀
	    $response['key'] = $path;
	    return $response;
	}
	protected function _gmt_iso8601($time) {
	    $dtStr = date("c", $time);
	    $mydatetime = new \DateTime($dtStr);
	    $expiration = $mydatetime->format(\DateTime::ISO8601);
	    $pos = strpos($expiration, '+');
	    $expiration = substr($expiration, 0, $pos);
	    return $expiration."Z";
	}
}